﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;

namespace Citi.Helpers
{
    public class SchedulerHelper
    {
        public static void RollbackRunner(Dictionary<string, object> parameters, string applicationPath)
        {
            var stopPath = parameters["StopPath"].ToString();
            var routineExecutionId = parameters["RoutineExecutionId"].ToString();

            var txtPath = Path.Combine(stopPath, string.Concat(routineExecutionId, ".txt"));

            File.WriteAllText(txtPath, applicationPath);
        }

        public static void StartRunner(Dictionary<string, object> parameters, string applicationPath)
        {
            var robotUsername = parameters["RobotUsername"].ToString();
            var robotPassword = parameters["RobotPassword"].ToString();
            var startPath = parameters["StartPath"].ToString();
            var routineExecutionId = parameters["RoutineExecutionId"].ToString();
            var applicationArguments = parameters.ContainsKey("ApplicationArguments") ? parameters["ApplicationArguments"].ToString() : null;
            var unlockLockMachine = parameters.ContainsKey("UnlockLockMachine") ? bool.Parse(parameters["UnlockLockMachine"].ToString()) : true;

            using (NetworkShareAccesser.Access(startPath, robotUsername, robotPassword))
            {
                var txtPath = Path.Combine(startPath, string.Concat(routineExecutionId, ".txt"));
                File.WriteAllLines(txtPath, new[] 
                { 
                    applicationPath, 
                    applicationArguments,
                    unlockLockMachine.ToString()
                });

                while (Process.GetProcessesByName(Path.GetFileNameWithoutExtension(applicationPath)).Length == 0)
                    Thread.Sleep(10000);

                while (Process.GetProcessesByName(Path.GetFileNameWithoutExtension(applicationPath)).Length > 0)
                    Thread.Sleep(10000);
            }
        }
    }
}
